//
//  CreatTopicController.m
//  Topic1
//
//  Created by 孙添凤 on 16/12/6.
//  Copyright © 2016年 孙添凤. All rights reserved.
//

#import "CreatTopicController.h"
#import "Masonry.h"
#import "OneSelectCell.h"
#import "TopicObjModel.h"
#import "NetRequest.h"
#import "AddModel.h"
#import "ListCell.h"
#import "SeleController.h"

@interface CreatTopicController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>{
    UITableView *tbView;
}
@property(nonatomic,strong)NSMutableArray *mutArr;
@property(nonatomic,strong)NSMutableDictionary *params;
@end

@implementation CreatTopicController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _mutArr =[NSMutableArray array];
    _params =[NSMutableDictionary dictionary];
    self.title = @"创建会话";
    self.view.backgroundColor =[UIColor whiteColor];
    
    tbView =[[UITableView alloc]init];
    [self.view addSubview:tbView];
    [tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    tbView.delegate = self;
    tbView.dataSource = self;
    UIButton *RightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    RightNavBtn.frame = CGRectMake(0, 0, 80, 30);
    [RightNavBtn setTitle:@"提交" forState:UIControlStateNormal];
    [RightNavBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [RightNavBtn addTarget:self action:@selector(RightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:RightNavBtn];
    self.navigationItem.rightBarButtonItem = item;
    [self createLeftNavBar];
    [self dataRequest];
    
}

-(NSString *)fieldDicToString:(NSArray *)arr isAdd:(BOOL)is{
    NSString *str = @"";
    NSMutableArray *array = [[NSMutableArray alloc]init];
    for(NSDictionary *dic in arr){
        NSArray *a1 =[dic allKeys];
        NSString *value =[dic objectForKey:a1[0]];
        NSString *equal = [NSString stringWithFormat:@"%@=%@",a1[0],value];
        [array addObject:equal];
    }
    if(!is){
        str =[array componentsJoinedByString:@"&"];
    }else{
        str =[array componentsJoinedByString:@"&&"];
        
    }
    return str;
}


-(void)RightClick:(UIButton *)btn{
    
    
    [_params setObject:@"17796" forKey:@"tableId"];
    [_params setObject:@"7687" forKey:@"pageId"];
    NSArray *arrrrr =[_params objectForKey:@"123"];
    [_params removeObjectForKey:@"123"];
    NSMutableArray *mmArr =[NSMutableArray array];
    NSArray *array =[_params allKeys];
    for(int i=0;i<array.count;i++){
        NSDictionary *dicd = [NSDictionary dictionaryWithObject:[_params objectForKey:array[i]] forKey:array[i]];
        [mmArr addObject:dicd];
    }
    [mmArr addObjectsFromArray:arrrrr];
    NSString *str = [self fieldDicToString:mmArr isAdd:YES];
    
    NSString *requesturl =[NSString stringWithFormat:@"%@%@?%@",BASE_URL,ADDTOPIC_URL,str];
    
    NSString * urlString= [requesturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url_str=[NSURL URLWithString:urlString];
    
    
    
    
    //    NSArray *arr = [_sendMutDic allKeys];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url_str];
    //    3.发送请求
    //发送异步请求，在主线程执行
    NSOperationQueue *queue=[NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(data!=nil&&!connectionError){
            NSString *dataStr=  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"创建会话成功" preferredStyle:UIAlertControllerStyleAlert];
            
            [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert2:) userInfo:alertController repeats:NO];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];

            
        }else{
            [self showLabelWithText:@"网络错误"];
            
            //*** hidden the netWork state activity
            [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
            
        }
    }];

    
   
}

- (void)creatAlert2:(NSTimer *)timer{
    
    UIAlertController *alert = [timer userInfo];
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    
    alert = nil;
    [self.navigationController popViewControllerAnimated:YES];
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddModel *model =[_mutArr objectAtIndex:indexPath.row];
    if(indexPath.row==2){
        SeleController *sv =[[SeleController alloc]init];
        sv.abc = ^(NSDictionary*a,NSArray*b,NSString *str){
            [_params addEntriesFromDictionary:a];
            ListCell *cell =[tableView cellForRowAtIndexPath:indexPath];
            cell.textView.text = str;
        };
        sv.dicArr = model.dicList;
        sv.montageName = model.montageName;
        sv.isMore = NO;
        [self.navigationController pushViewController:sv animated:YES];
    }else if (indexPath.row==1){
        SeleController *sv =[[SeleController alloc]init];
        sv.abc = ^(NSDictionary*a,NSArray*b,NSString *str){
            [_params setObject:b forKey:@"123"];
            [_params setObject:[NSString stringWithFormat:@"%lu",(unsigned long)b.count] forKey:model.montageName];
            ListCell *cell =[tableView cellForRowAtIndexPath:indexPath];
            cell.textView.text = str;
        };
        sv.dicArr = model.dicList;
        sv.montageName1 = model.montageName1;
       
        sv.isMore = YES;
        [self.navigationController pushViewController:sv animated:YES];
    }
}


-(void)dataRequest{
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:@"17796" forKey:@"tableId"];
    [params setObject:@"7687" forKey:@"pageId"];
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,ADDMF_URL];
    [NetRequest requestUrl:requestUrl andParamas:params andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
            NSDictionary *obj =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *arr = [[obj objectForKey:@"pageSet"]objectForKey:@"fieldSet"];
          
            for(NSDictionary *dic in arr){
                AddModel *model =[[AddModel alloc]init];
                model.fieldCnName = [dic objectForKey:@"fieldCnName"];
                model.ifMust =[dic objectForKey:@"ifMust"];
                model.montageName =[dic objectForKey:@"montageName"];
                model.montageName1 =[dic objectForKey:@"montageName1"];
                model.dicList =[dic objectForKey:@"dicList"];
                [_mutArr addObject:model];
            }
            
            
            
            [tbView reloadData];
        }else{
            
        }
    }];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _mutArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str = @"str";
    ListCell *cell =[tableView dequeueReusableCellWithIdentifier:str];
    if(cell==nil){
        cell=[[ListCell alloc]initIdentifier:str];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    AddModel *model = [_mutArr objectAtIndex:indexPath.row];
    cell.la.text = model.fieldCnName;
    cell.textView.tag = 10000+indexPath.row;
    cell.textView.delegate = self;
    NSLog(@"%@",model.dicList);
    if(indexPath.row==2){
        cell.textView.placeholder = @"请选择";
        cell.contentView.userInteractionEnabled = NO;
    }else if (indexPath.row==1){
        cell.textView.placeholder = @"请选择";
        cell.contentView.userInteractionEnabled = NO;
    }
    return cell;
    
}


-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    return YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView{
     NSInteger index = textView.tag-10000;
    AddModel *model = [_mutArr objectAtIndex:index];
    [_params setObject:textView.text forKey:model.montageName];
   
    
}

-(BOOL)textView:(CustomTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)createLeftNavBar{
    UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftNavBtn.frame = CGRectMake(0, 0, 11, 37/2);
    [leftNavBtn setBackgroundImage:[UIImage imageNamed:@"形状1-19-拷贝-4"] forState:UIControlStateNormal];
    [leftNavBtn addTarget:self action:@selector(LeftClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftNavBtn];
    self.navigationItem.leftBarButtonItem = item;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
